package com.zhibi.util.codec.aes;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import com.zhibi.util.codec.common.HexStrUtil;

public class AESUtil {

	/**
	 * 加密
	 * @param content 要加密的内容
	 * @param key 密钥
	 * @return
	 */
	public static String encrypt(String content, String key,String charset) {  
		if(charset==null || charset.isEmpty()){
			charset = "utf-8";
		}
		try {             
			KeyGenerator kgen = KeyGenerator.getInstance("AES");  
			kgen.init(128, new SecureRandom(key.getBytes()));  
			SecretKey secretKey = kgen.generateKey();  
			byte[] enCodeFormat = secretKey.getEncoded();  
			SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, "AES");  
			Cipher cipher = Cipher.getInstance("AES");// 创建密码器   
			byte[] byteContent = content.getBytes(charset);  
			cipher.init(Cipher.ENCRYPT_MODE, keySpec);// 初始化   
			byte[] result = cipher.doFinal(byteContent);  
			return HexStrUtil.parseByte2HexStr(result); // 加密   
		} catch (Exception e) {  
			e.printStackTrace();  
		}
		return null;  
	}

	/**
	 * 解密
	 * @param content
	 * @param key
	 * @return
	 */
	public static String decrypt(String content, String key,String charset) { 
		if(charset==null || charset.isEmpty()){
			charset = "utf-8";
		}
		try {  
			KeyGenerator kgen = KeyGenerator.getInstance("AES");  
			kgen.init(128, new SecureRandom(key.getBytes()));  
			SecretKey secretKey = kgen.generateKey();  
			byte[] enCodeFormat = secretKey.getEncoded();  
			SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, "AES");              
			Cipher cipher = Cipher.getInstance("AES");// 创建密码器   
			cipher.init(Cipher.DECRYPT_MODE, keySpec);// 初始化   
			byte[] result = cipher.doFinal(HexStrUtil.parseHexStr2Byte(content));  
			return new String(result,charset); // 加密   
		} catch (Exception e) {  
			e.printStackTrace();  
		}
		return null;  
	}  
}
